package tech.jabari.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 数据源工具类
 * @author Jabari Lu
 * @title: DataSourceUtil
 * @data 2020/8/21 10:05
 */
@Component
public class DataSourceUtil {

    public static final String PROPERTIES_FILENAME = "db.properties";
    public static Properties properties = new Properties();

    /**
     * 获取DruidDataSource
     * @return
     */
    public static DataSource getDataSource(){
        DruidDataSource ds = null;
        // 1.获取InputStream（包含数据库配置信息文件的字节输入流）
        InputStream is = DataSourceUtil.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
        // 2.加载InputStream到Properties
        try {
            properties.load(is);
            //3. 创建DruidDataSource
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            // 4. 可选操作（url）
            String jdbcUrl = properties.getProperty("jdbc.url");
            ds.setUrl(jdbcUrl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ds;
    }





}
